package network.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class HttpClient {
    private Socket socket = null;

    public HttpClient(String serverIp,int port) throws UnknownHostException, IOException{
        socket = new Socket(serverIp,port);
    }

    //通过get方法发起一个HTTP GET 请求
    public void get(String url) throws IOException {
        //构造HTTP结构的字符串·
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();){
            String firstLine = "GET " + url + " HTTP/1.1\n";
            String headers = "Host: " + socket.getInetAddress().getHostName() + ":" + socket.getPort() + "\n";
            String blankLine = "\n";
            String httpRequest = firstLine + headers + blankLine;

            outputStream.write(httpRequest.getBytes());
            outputStream.flush();

            //发送出请求之后，还需要读取响应
            byte[] bytes = new byte[1024 * 1024];
            int n = inputStream.read(bytes);
            String httpResponse = new String(bytes,0,n);
            System.out.println(httpResponse);

        }catch(IOException e){
            e.printStackTrace();
        }
        return ;
    }

    public static void main(String[] args) {
        
    }
    
}
